#include "ColorPicker.hpp"

#include <QColorDialog>
#include <QHBoxLayout>
#include <QLineEdit>
#include <QMessageBox>
#include <QPixmap>
#include <QRegularExpressionValidator>
#include <QWidget>

#include "ClickableLabel.hpp"

ColorPicker::ColorPicker(QColor initColor, QWidget *parent)
    : color(initColor),
      QWidget(parent)
{
    this->setupUI();
    this->connectSignals();
    this->setColor(initColor);
}

void ColorPicker::onColorSetButtonClicked()
{
    if (this->colorDialog->exec() == QDialog::Accepted) {
        this->setColor(this->colorDialog->currentColor());
    }
}

void ColorPicker::setupUI()
{
    auto mainLayout         = new QHBoxLayout{this};
    this->colorPreviewLabel = new ClickableLabel{this};
    this->colorPreviewLabel->setFixedSize(20, 20);
    this->colorPreviewLabel->setFrameStyle(QFrame::Box);
    this->colorPreviewLabel->setLineWidth(1);
    mainLayout->addWidget(this->colorPreviewLabel);

    this->colorHexValueLabel = new QLabel{this};
    mainLayout->addWidget(this->colorHexValueLabel);
    mainLayout->addStretch();

    this->colorDialog = new QColorDialog{this};
    this->colorDialog->setWindowTitle("Select Color");
    this->colorDialog->setCurrentColor(this->color);
}

void ColorPicker::connectSignals()
{
    QObject::connect(this->colorPreviewLabel,
                     &ClickableLabel::clicked,
                     this,
                     &ColorPicker::onColorSetButtonClicked);
}

void ColorPicker::setColor(const QColor &color)
{
    this->color = color;

    // 更新预览框
    QPixmap pixmap{30, 30};
    pixmap.fill(color);
    this->colorPreviewLabel->setPixmap(pixmap);

    // 更新十六进制值
    this->colorHexValueLabel->setText(color.name(QColor::HexRgb).toUpper());

    emit colorChanged(color); // 发出颜色改变信号
}

QColor ColorPicker::getColor() const
{
    return this->color;
}
